package com.aerozhonghuan.logisticsmall.modules.home.search;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.modules.common.IMainView;
import com.aerozhonghuan.logisticsmall.modules.common.MainActivity;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.entity.ProductImg;
import com.aerozhonghuan.logisticsmall.modules.common.event.TabNumberChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.home.GoodsDetailsActivity;
import com.aerozhonghuan.logisticsmall.utils.CommunityTool;
import com.aerozhonghuan.logisticsmall.utils.CommunityUtils;
import com.aerozhonghuan.logisticsmall.utils.StatisticsConstant;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ChenLin on 2019/5/22 10:05.Email&WeChat:7877409@163.com
 */
public class ProductListAdapter extends BaseAdapter {

    private RequestOptions options;
    int mAppIndex = 101;
    private List<GoodsObject> list = new ArrayList<GoodsObject>();
    private Activity mActivity;
    private DBAdapter mDbAdapter;
    private String mFrom;
    View.OnClickListener mProductInfoListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            GoodsObject object = (GoodsObject) v.getTag();
            Intent intent = new Intent(mActivity,
                    GoodsDetailsActivity.class);
            intent.putExtra("pvsid", object.getPvsid());
            intent.putExtra("from", mFrom);
            mActivity.startActivity(intent);
        }
    };
    private LayoutInflater mInflater;
    private int mSourceId;
    private int[] mSectionIndices;
    private boolean isVisibleStock;

    public ProductListAdapter(Activity c, DBAdapter dbAdapter, String from, int sourceId) {
        mActivity = c;
        mDbAdapter = dbAdapter;
        mFrom = from;
        mInflater = LayoutInflater.from(c);
        mSourceId = sourceId;
        switch (mSourceId) {
            case 1:
                mAppIndex = 101;
                break;
            case 2:
                mAppIndex = 101;
                break;
            case 3:
                mAppIndex = 102;
                break;
            case 4:
                mAppIndex = 110;
                break;
            case 5:
                mAppIndex = 103;
                break;
            case 6:
                mAppIndex = 102;
                break;
            case 7:
                mAppIndex = 106;
                break;
            case 8:
                mAppIndex = 419;
                break;
            case 9:
                mAppIndex = 409;
                break;
            case 10:
                mAppIndex = 102;
                break;
            default:
                break;
        }
        options = new RequestOptions().placeholder(R.mipmap.ic_goods_placehoder_little).error(R.mipmap.ic_goods_placehoder_little);
    }

    public void setData(List<GoodsObject> goodsObject) {
        if (goodsObject == null || goodsObject.size() == 0) {
            list.clear();
        } else {
            list = goodsObject;
        }
        notifyDataSetChanged();
        //实现section效果，得到sections
        //mSectionIndices = getSectionIndices();
    }

    public List<GoodsObject> getListData() {
        return list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final Holder holder;
        if (convertView == null) {
            //convertView = mInflater.inflate(R.layout.type_item, null);
            convertView = mInflater.inflate(R.layout.type_item2, parent, false);
            holder = new Holder();
            holder.icon = (ImageView) convertView
                    .findViewById(R.id.type_icon);
            holder.textView = (TextView) convertView
                    .findViewById(R.id.type_title);
            holder.priceView = (TextView) convertView
                    .findViewById(R.id.type_price);
            holder.disCountPriceView = (TextView) convertView
                    .findViewById(R.id.discount_price);
            holder.buyView = (ImageView) convertView.findViewById(R.id.buy);
            holder.gouwucheSizeView = (TextView) convertView.findViewById(R.id.gouwuchesize_view);
            holder.minusNumberView = (ImageView) convertView.findViewById(R.id.minus_number);
            holder.productInfoView = (View) convertView
                    .findViewById(R.id.product_info);
            holder.quantityAvailable = (TextView) convertView.findViewById(R.id.quantity_available);
            holder.productSize = (TextView) convertView.findViewById(R.id.product_size);
            holder.jiaobiaoRight = (ImageView) convertView.findViewById(R.id.jiaobiao_right);
            convertView.setTag(holder);
        } else {
            holder = (Holder) convertView.getTag();
        }
        final GoodsObject product = list.get(position);
        holder.icon.setImageResource(R.mipmap.def_img);
        List<ProductImg> pImageList = product.getpImageList();
        int productImgId = 0;
        if (pImageList != null && pImageList.size() > 0) {
            for (ProductImg productImg : pImageList) {
                if (productImg.is_thumbnail == 1) {
                    productImgId = productImg.imgid;
                    break;
                } else {
                    productImgId = productImg.imgid;
                }
            }
        }
        String imgUrl = CommunityTool.changeImageId(productImgId, true, false);

        if (com.blankj.utilcode.util.AppUtils.isAppDebug()) {
            Log.d("community2", "imgUrl>>>>>>>>>>:" + imgUrl);
        }
        Glide.with(mActivity).load(imgUrl).apply(options).into(holder.icon);

        holder.textView.setText(product.getBaseName());
        holder.priceView.setText("￥ " + product.getPrice() / 100f);
        holder.disCountPriceView.setText("原价:" + product.getOldPrice() / 100f);
        if (product.getOldPrice() == product.getPrice()) {
            holder.disCountPriceView.setVisibility(View.GONE);
        } else {
            holder.disCountPriceView.setVisibility(View.VISIBLE);
        }
        holder.disCountPriceView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

        int quantityAvailabel = product.getQuantityAvailable();
        holder.productSize.setText(quantityAvailabel + "");

        int jiaoImgId = product.getTriangle();
        Log.d("jiaobiao", "jiaoImgId==productListAdapter" + jiaoImgId);
        if (jiaoImgId != 0) {
            holder.jiaobiaoRight.setVisibility(View.VISIBLE);
            String jiaobiaoUrl = CommunityTool.changeOthersImageId(jiaoImgId, 126, "triangle");
            //Log.d("jiaobiao", "jiaobiaoUrl=="+jiaobiaoUrl);
            Glide.with(mActivity).load(jiaobiaoUrl).apply(options).into(holder.jiaobiaoRight);
        } else {
            holder.jiaobiaoRight.setVisibility(View.INVISIBLE);
        }

        if (isVisibleStock) {
            holder.productSize.setVisibility(View.VISIBLE);
        } else {
            holder.productSize.setVisibility(View.INVISIBLE);
        }

        if (quantityAvailabel <= 0) {
            holder.buyView.setVisibility(View.GONE);
            holder.quantityAvailable.setVisibility(View.VISIBLE);
        } else {
            holder.buyView.setVisibility(View.VISIBLE);
            holder.quantityAvailable.setVisibility(View.GONE);
            //判断购物车中是否有商品，以显示减号
            if (product.getIntoGouwucheSize() > 0) {
                holder.gouwucheSizeView.setVisibility(View.VISIBLE);
                holder.gouwucheSizeView.setText(product.getIntoGouwucheSize() + "");
                holder.minusNumberView.setVisibility(View.VISIBLE);
                holder.buyView.setSelected(true);
            } else {
                holder.gouwucheSizeView.setVisibility(View.GONE);
                holder.minusNumberView.setVisibility(View.GONE);
                holder.buyView.setSelected(false);
            }
        }
        holder.buyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.setSelected(true);
                int productSize = CommunityUtils.addProductToGouwuche(mActivity, product, new DBAdapter(mActivity), mSourceId);
                int pGouwucheSize = product.getIntoGouwucheSize();
                if (pGouwucheSize <= product.getQuantityAvailable()) {
                    /*if (mGouwucheView != null) {不要动画
                        AddGouwucheUtil.getInstance().setAnim(mActivity, holder.icon.getDrawable(), holder.icon, mGouwucheView);
                    }*/
                    if (!holder.gouwucheSizeView.isShown()) {
                        holder.gouwucheSizeView.setVisibility(View.VISIBLE);
                        holder.minusNumberView.setVisibility(View.VISIBLE);
                        holder.gouwucheSizeView.setText(pGouwucheSize + "");
                    } else {
                        holder.gouwucheSizeView.setText(pGouwucheSize + "");
                    }
                    EventBusManager.post(new TabNumberChangedEvent(IMainView.TAB_CART_FRAGMENT, productSize));
                    StatisticsConstant.getInstance().ClickActionParams(4, mAppIndex, String.valueOf(product.getPvsid()));
                } else {
                    StatisticsConstant.getInstance().ClickActionParams(5, mAppIndex, String.valueOf(product.getPvsid()));
                    ToastUtils.showShort("库存不足了，先买这么多吧!");
                }
            }
        });
        holder.minusNumberView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                int productCurNumber = product.getIntoGouwucheSize() - 1;
                if (productCurNumber == 0) {
                    holder.buyView.setSelected(false);
                    holder.gouwucheSizeView.setVisibility(View.GONE);
                    holder.minusNumberView.setVisibility(View.GONE);
                    //删除购物车中该商品
                    mDbAdapter.deleteTitle(String.valueOf(product.getPvsid()));
                } else {
                    holder.gouwucheSizeView.setText(productCurNumber + "");
                }
                product.setIntoGouwucheSize(productCurNumber);
                mDbAdapter.open().updateGouwuche(product.getPvsid(), CommunityUtils.USER_ID, CommunityTool.saveObject(product));
                if (MainActivity.getCarNum() == 0) {
                    return;
                }
                int curGouwucheAllNumber = MainActivity.getCarNum() - 1;
                if (curGouwucheAllNumber != 0) {
                    EventBusManager.post(new TabNumberChangedEvent(IMainView.TAB_CART_FRAGMENT, curGouwucheAllNumber));
                }
            }
        });
        holder.productInfoView.setOnClickListener(mProductInfoListener);
        holder.productInfoView.setTag(product);

        //超市页面添加的空商品
        /*if (product.getAliasCid() == 0) {
        	holder.productInfoView.setVisibility(View.INVISIBLE);
		}else {
			holder.productInfoView.setVisibility(View.VISIBLE);
		}*/

        return convertView;
    }

    class Holder {
        ImageView icon;
        TextView textView;
        TextView priceView;
        TextView disCountPriceView;
        ImageView buyView;
        TextView gouwucheSizeView;
        ImageView minusNumberView;
        View productInfoView;
        TextView quantityAvailable;
        TextView productSize;
        ImageView jiaobiaoRight;
    }

}
